#!/usr/bin/env python3
# ezpp text2icon -t "智课"  -c "#fff"  -b "#f93" -o "./playground/ZK.png"
# ezpp resize -i ./playground/ZK.png -s 256

from PIL import Image, ImageColor
import sys
from ezutils.colors import *

COLOR_SAME_RADUS = 128


def sameColor(colorA, colorB):
    # return colorA == colorB
    r = colorA[0] - colorB[0]
    g = colorA[1] - colorB[1]
    b = colorA[2] - colorB[2]
    return r*r+g*g+b*b < COLOR_SAME_RADUS*COLOR_SAME_RADUS


def shadowColor(colorbg):
    r, g, b = colorbg
    h, s, v = rgb2hsv(r, g, b)
    r1, g1, b1 = hsv2rgb(h, s, v/2)
    # rgb = str(bytearray([r1, g1, b1]))
    # strHex = f'#{rgb}'
    # print('strHex', strHex)
    strHex = bytearray([r1, g1, b1]).hex()
    return f"#{strHex}"


def shadowOnline(pixes, width, height, fromX, fromY):
    first = None
    firstObj = None
    for i in range(0, width):
        x = fromX+i
        y = fromY+i
        if x >= width or y >= height:
            continue

        if first == None:
            first = pixes[x, y]
            # print(f'first{x},{y}', first)
            continue

        if firstObj == None:
            if not sameColor(first, pixes[x, y]):
                firstObj = pixes[x, y]
            continue

        if sameColor(first, pixes[x, y]):
            pixes[x, y] = ImageColor.getcolor(shadowColor(pixes[x, y]), "RGB")


def shadowOnPixes(pixes, width, height):
    # shadowOnline(pixes, width, height, 0, 0)
    for i in range(0, width):
        shadowOnline(pixes, width, height, i, 0)

    for j in range(0, height):
        shadowOnline(pixes, width, height, 0, j)


def shadowOnImage(img):
    imgSize = img.size
    pixes = img.load()
    width, height = imgSize
    shadowOnPixes(pixes, width, height)


def shadow(fileName,outFile):
    with Image.open(fileName) as im:
        shadowOnImage(im)
        im.show()
        im.save(outFile)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        shadow(sys.argv[1], f"{sys.argv[1]}_shadow.png")
    elif len(sys.argv) > 2:
        shadow(sys.argv[1], sys.argv[2])
    else:
        shadow("./playground/ZK.png","./playground/ZK_shadow.png")
